<?php
/**
 * Created by PhpStorm.
 * User: wchuang
 * Date: 2016/8/24
 * Time: 11:39
 */
namespace common\services;

use yii;
use common\models\LydbUser;
use yii\db\Exception;
use yii\validators;
class UserService extends NetService
{
	/**
	 * @var string 默认用户密码
	 */
	public static $defualtPassword = "8uhb9ijn";

	public static $mobilePrefix = ['13','15','17','18'];


	public function __construct()
	{
	}

	private function __generateMobile($prefix = '')
	{
		if(!in_array($prefix,self::$mobilePrefix)){
			$prefix  = self::$mobilePrefix[mt_rand(0,count(self::$mobilePrefix)-1)];
		}


		return $prefix . mt_rand(100000000,999999999);
	}

	/**
	 * 登陆远程应用
	 *
	 * @param $phone //登陆的手机号码
	 * @param $password //登陆的密码
	 * @return null
	 */
	public function remoteUserLogin($phone, $password){
		$requestUrl = self::SERVER_URL . "/xingluo/rest/app_lydb/user/login";
		if(is_numeric($phone) && $phone && $password){
			$response = $this->reset()
				->setOption(
					CURLOPT_POSTFIELDS,
					http_build_query(array(
							'phone'     => $phone,
							'password'  =>  $password
						)
					))
				->post($requestUrl);
			return json_decode($response,true);
		}else{
			return null;
		}
	}

	/**
	 * 创建远程应用用户
	 * @param $phone
	 * @param $password
	 * @return null
	 */
	public function remoteUserCreate($phone, $password){
		$requestUrl = self::SERVER_URL . "/xingluo/rest/app_lydb/user/register";
		if(is_numeric($phone) && $phone && $password){
			$response = $this->reset()
				->setOption(
					CURLOPT_POSTFIELDS,
					http_build_query(array(
							'phone'     => $phone,
							'password'  =>  $password,
							'isTrue'    => true
						)
					))
				->post($requestUrl);
			return json_decode($response,true);
		}else{
			return null;
		}
	}

	/**
	 * 创建一个虚拟用户
	 * @return bool
	 */
	public function userCreate(){
		$phone = $this->__generateMobile();
		$password = self::$defualtPassword;


		//test
//		$lydbUser = new LydbUser();
//		$lydbUser->mobile   = $phone;
//		$lydbUser->password = $password;
//		$lydbUser->create_time = time();
//		$lydbUser->lydb_id  = '123' . $phone;
//
//		try{
//			return $lydbUser->save();
//		}catch (Exception $e){
//			return false;
//		}
		$res = $this->remoteUserCreate($phone,$password);
		if($res && $res['code'] == 0){
			$lydbUser = new LydbUser();
			$lydbUser->mobile   = $phone;
			$lydbUser->password = $password;
			$lydbUser->create_time = time();

			$loginRes = $this->remoteUserLogin($phone,$password);
			if($loginRes && $loginRes['code'] == 0 && isset($loginRes['attributes'][0])){
				$userInfo = $loginRes['attributes'][0];
				$lydbUser->lydb_id  = $userInfo['id'];
				$lydbUser->data     = json_encode($userInfo);
			}
			try{
				return $lydbUser->save();
			}catch (Exception $e){
				return false;
			}
		}else{
			return false;
		}

	}

	/**
	 * 获取用户的远程应用token
	 * @param $user
	 * @return null
	 */
	public function getToken($user){
		if(!is_object($user)){
			return null;
		}
		$cache = YII::$app->cache;
		$cache->keyPrefix = 'Remote_Token';

		$token =$cache->get('_' . $user->mobile);
		if(!$token){
			$loginRes = $this->remoteUserLogin($user->mobile,$user->password);
			if($loginRes && $loginRes['code'] == 0){
				$token = $loginRes['token'];
				$cache->set('_' . $user->mobile,$token,36000);

				return $token;
			}
		}

		return $token;
	}

	public function userMultiCreate($maxNum = 1){
		if(is_numeric($maxNum) && $maxNum > 0){
			$index = 0;
			$indexOk = 0;


			while($index < $maxNum){
				$args = [
					'action'    =>  'createUser',
					'args'      =>  ''
				];
				\common\queue\Queue::newQueue('UserJob',$args);

//				if($this->userCreate()){
//					$indexOk++;
//				}

				$index++;
			}

			return $indexOk;
		}else{
			return 0;
		}
	}
	
}